import React, { useContext } from 'react';
import { Table, Tag } from 'antd';
import classnames from 'classnames';
import { uniqueId, groupBy } from 'lodash';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { getRangeDescription } from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/rangeDescription';
import { numberFormat } from '@/utils/formatterUtil';

import BaseSettingContext from './BaseSettingContext';
import style from './index.less';

const STATUS = {
    NORMAL: 0,
    ADD: 1,
    DELETE: 2,
    EDIT: 3
};
const MODIFY_STATUS = {
    // 正常
    [STATUS.NORMAL]: {
        tag: null,
        rowTheme: null
    },
    // 新增
    [STATUS.ADD]: {
        tag: {
            text: '新增',
            color: 'cyan'
        },
        rowTheme: 'add'
    },
    // 删除
    [STATUS.DELETE]: {
        tag: {
            text: '删除',
            color: 'red'
        },
        rowTheme: 'delete'
    },
    // 编辑
    [STATUS.EDIT]: {
        tag: {
            text: '编辑',
            color: 'blue'
        },
        rowTheme: null
    }
};

const onFieldCell = field => record =>
    record?.[field] === 1 ? { 'data-cell-theme': 'modified' } : { 'data-cell-theme': '' };

/**
 * 表格列定义
 * @returns []
 */
const tableColumn = (showCompareEffect, scale) => [
    {
        title: '雇员该自然月薪资总额',
        dataIndex: '_amtLevel',
        width: 200,
        onCell: onFieldCell('twPeriodEditStatus'),
        render(text, record) {
            const statusMapperInfo = MODIFY_STATUS[record.editStatus] ?? MODIFY_STATUS[STATUS.NORMAL];
            const tagInfo = showCompareEffect ? statusMapperInfo.tag : MODIFY_STATUS[STATUS.NORMAL];
            return (
                <>
                    <span className={style.mr8}>
                        <EmptyPlaceHolder
                            value={getRangeDescription(
                                numberFormat(record.twStartAmt, scale),
                                record.twStartAmtSign,
                                numberFormat(record.twEndAmt, scale),
                                record.twEndAmtSign,
                                '$'
                            )}
                        />
                    </span>
                    {tagInfo ? <Tag color={tagInfo.color}>{tagInfo.text}</Tag> : null}
                </>
            );
        },
        ellipsis: true
    },
    {
        title: '雇员扣除额',
        dataIndex: 'shgAmt',
        width: 100,
        onCell: onFieldCell('shgAmtEditStatus'),
        render(text) {
            return (
                <span className={style.mr8}>
                    {text ? numberFormat(text, scale, ',', '.', '$') : <EmptyPlaceHolder />}
                </span>
            );
        },
        ellipsis: true
    }
];

const getGroupKey = item => item?.id;

const wrapDataSource = dataList => {
    const allData = [].concat(dataList);
    const dataGroup = groupBy(allData, 'id');

    return allData.map((item, index, arr) => {
        const preItem = index === 0 ? null : arr[index - 1];
        return {
            ...item,
            id: item.id || uniqueId('id'),
            v_rowSpan: getGroupKey(preItem) !== getGroupKey(item) ? dataGroup[getGroupKey(item)].length : 0
        };
    });
};

const TableWrapper = ({
    columns,
    dataSource,
    showCompareEffect,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const tableProps = {
        onRow: record => ({
            className: classnames({
                'row-hover': hoverRow && getGroupKey(hoverRow.row) === getGroupKey(record),
                'row-cell-hover': hoverRow && hoverRow.row.id === record.id,
                'row-selected': selectedRow && selectedRow.row.id === record.id
            }),
            onClick: () => {
                setCurrentSelectedRow({ position: comparePosition, row: record });
            },
            onMouseEnter: () => {
                setCurrentHoverRow({ position: comparePosition, row: record });
            },
            onMouseLeave: () => {
                setCurrentHoverRow(null);
            },
            'data-row-theme': showCompareEffect
                ? (MODIFY_STATUS[record?.editStatus] || MODIFY_STATUS[STATUS.NORMAL])?.rowTheme || ''
                : ''
        })
    };

    return (
        <div>
            <Table
                size="small"
                tableLayout="fixed"
                columns={columns}
                rowKey="id"
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                bordered
                {...tableProps}
            />
        </div>
    );
};

const CompareItem = ({
    dataSource,
    showCompareEffect = false,
    comparePosition,
    hoverRow,
    selectedRow,
    setCurrentHoverRow,
    setCurrentSelectedRow
}) => {
    const {
        contextState: { scale = 2 }
    } = useContext(BaseSettingContext);
    return (
        <div className="compare-item">
            <TableWrapper
                columns={tableColumn(showCompareEffect, scale)}
                dataSource={wrapDataSource(dataSource)}
                showCompareEffect={showCompareEffect}
                pagination={false}
                comparePosition={comparePosition}
                hoverRow={hoverRow}
                selectedRow={selectedRow}
                setCurrentHoverRow={setCurrentHoverRow}
                setCurrentSelectedRow={setCurrentSelectedRow}
            />
        </div>
    );
};

export default CompareItem;
